package com.bwie;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @description : 使用synchronized关键字保护共享资源
 * @Author QiHainan
 * @Create 2025/6/28 11:02
 * @Version 1.0
 */
public class BookList1 {
    private List<Book> bookList = new ArrayList<>();

    public synchronized Book adBook(Book book){
        bookList.add(book);
        return book;
    }

    public synchronized Book getBook(int index){
        return bookList.get(index);
    }

    public synchronized Book removeBook(int index){
        return bookList.remove(index);
    }

    public void printAll(){
        for (Book book : bookList) {
            System.out.println(book);
        }
    }

    @Test
    public void testBookList1(){
        BookList1 bookList = new BookList1();

        //添加图书
        bookList.adBook(new Book("1","title1","author1","publisher1"));
        bookList.adBook(new Book("2","title2","author2","publisher2"));
        bookList.adBook(new Book("3","title3","author3","publisher3"));

        System.out.println(bookList.getBook(1));

        //删除,id=1
        bookList.removeBook(1);

        //打印
        bookList.printAll();
    }
}
